package demo17_SinglePattern;

import java.lang.reflect.Constructor;

/**
 * @author kunkun
 * @className Test02_Lazy_common
 * @Description 单例模式---懒汉式---展示问题（通过红绿灯法修改）
 * @date 2025/3/8 13:12
 */
public class Test05_Lazy_problem {

    private volatile static Test05_Lazy_problem hungry ;//避免指令重排，加上Volatile

    private static boolean flag=false;

    private Test05_Lazy_problem(){
        synchronized(Test05_Lazy_problem.class){
            if (flag){
                throw new RuntimeException("避免使用反射破坏单例模式");
            }else {
                flag=true;
            }
        }
        System.out.println("调用无参构造");
    }

    public static Test05_Lazy_problem getInstance(){
        if (hungry==null){
            synchronized (Test05_Lazy_problem.class){
                if (hungry==null){
                    hungry = new Test05_Lazy_problem();
                }
            }
        }
        return hungry;
    }

    public static void main(String[] args) throws Exception {
        //通过懒汉式创建对象
//        Test04_Lazy_problem.getInstance();

        Class<Test05_Lazy_problem> aClass = Test05_Lazy_problem.class;
        Constructor<Test05_Lazy_problem> constructor = aClass.getDeclaredConstructor(null);
        constructor.setAccessible(true);
        Test05_Lazy_problem instance1 = constructor.newInstance();
        Test05_Lazy_problem instance2 = constructor.newInstance();
    }
}
